import $ from 'jquery'

var _original = $.post;
$.post = function(url, params) {
    if ($.isPlainObject(params) && $.isPlainObject(params.args)) {
        params.args = JSON.stringify(params.args);
    }
    return _original.apply(this, arguments);
}


var constant = {
    IDLE: 'idle',
    LOADING: 'loading',
    ERROR: 'fail',
    BUSY: 'busy_now'
}

export {constant}

export default {
    data() {
        var vm = this;
        return {
            autoClear: true,
            state: constant.IDLE,
            lastState: null,
            lastRes: null,
            ajaxUID: 0,
            hasFile: false,
            fail: $.Callbacks("unique stopOnFalse").add(function() {
                vm.state = constant.ERROR;
            }),
            succeed: $.Callbacks("unique stopOnFalse").add(function(res) {
                vm.state = constant.IDLE;
            }),
            after: $.Callbacks("unique stopOnFalse").add(function(res, state) {
                vm.ajaxUID++;
                vm.lastState = state;
                if (state == 'success') {
                    vm.lastRes = res;
                } else if (state == 'error') {
                    vm.lastRes = res.responseJSON || res.responseText || res;    
                }
                
            }),
        }
    },
    computed: {
        isLoading() {
            return this.state == constant.LOADING;
        },
        isFailed() {
            return this.state == constant.ERROR;
        },
        isSucceed() {
            return this.lastState ? this.lastState === 'success' : false
        },
    },
    methods: {
        clearState() {
            this.state = constant.IDLE;
        },
        ajaxPost() {
            var vm = this;
            if (vm.state != constant.IDLE) {
                if (vm.autoClear && vm.state == constant.ERROR) {
                    vm.clearState();
                } else {
                    return $.Deferred(w => w.reject(vm.state)).promise();
                }
            }
            vm.state = constant.LOADING;
            var promise = vm.hasFile ? $.ajax(
                {
                    url: arguments[0],
                    data: arguments[1],
                    type: "POST",
                    contentType: false,
                    processData: false
                }
            ) : $.post.apply($, arguments);
            promise
            .done(vm.succeed.fire)
            .fail(vm.fail.fire)
            .always(vm.after.fire)
            return promise;
        }
    }
}